/*
 * Copyright 2009 Julian Mendez
 *
 *
 * This file is part of CEL Plug-in.
 *
 * CEL Plug-in is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * CEL Plug-in is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with CEL Plug-in.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package de.tudresden.inf.lat.cel.connection;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.semanticweb.owlapi.reasoner.OWLReasonerConfiguration;

/**
 * This class reads the output generated by the CEL reasoner. If there is a
 * ProgressMonitor, this class updates its value.
 * 
 * @author Julian Mendez
 */
class CelProcessOutputHandler extends Thread {

	/** Character sent by CEL to show progress. */
	public static final char countingChar = '#';

	private static final Logger logger = Logger
			.getLogger(CelProcessOutputHandler.class.getName());

	private static final int maxProgress = 100;

	private boolean active = false;
	private OWLReasonerConfiguration configuration = null;
	private InputStream input = null;
	private CelOutputListener listener = null;

	private OutputStream output = null;

	/** Time for reading the output of the CEL reasoner. */
	private long pollingPeriod = 1000;

	/**
	 * Creates a new instance.
	 * 
	 * @param in
	 *            input to be read.
	 * @param out
	 *            output used to write what was read.
	 */
	public CelProcessOutputHandler(InputStream in, OutputStream out) {
		this.input = in;
		this.output = out;
	}

	public CelOutputListener getOutputListener() {
		return this.listener;
	}

	public OWLReasonerConfiguration getReasonerConfiguration() {
		return this.configuration;
	}

	public boolean isActive() {
		return this.active;
	}

	/**
	 * Reads the output of the CEL reasoner and updates the values of the
	 * ProgressMonitor.
	 */
	@Override
	public void run() {
		try {
			int progress = 0;
			this.active = true;
			while (isActive()) {
				Thread.sleep(this.pollingPeriod);
				if (this.input.available() > 0) {
					StringBuffer sbuf = new StringBuffer();
					int ch = ' ';
					while (isActive() && (this.input.available() > 0)
							&& (ch != -1)) {
						ch = this.input.read();
						if (ch != -1) {
							if (getReasonerConfiguration() != null
									&& getReasonerConfiguration()
											.getProgressMonitor() != null) {
								if (ch == countingChar) {
									getReasonerConfiguration()
											.getProgressMonitor()
											.reasonerTaskProgressChanged(
													progress, maxProgress);
									progress++;
								}
							}
							sbuf.append((char) ch);
						}
					}
					sbuf.append("\n");
					if (logger.isLoggable(Level.FINER)) {
						this.output.write(sbuf.toString().getBytes());
					}
				}
			}
		} catch (IOException e) {
			logger.log(Level.WARNING, "Cannot show output.", e);
		} catch (InterruptedException e) {
			logger.log(Level.WARNING, "Process was interrupted.", e);
		}
		if (getOutputListener() != null) {
			getOutputListener().notifyExecutionFinished();
		}
	}

	public void setOutputListener(CelOutputListener outputListener) {
		this.listener = outputListener;
	}

	public void setReasonerConfiguration(OWLReasonerConfiguration config) {
		this.configuration = config;
	}

	/**
	 * Stops the execution of this thread.
	 */
	public void stopExecution() {
		this.active = false;
	}
}
